package com.zx.mes.hyl.array;

/**
 * Array int 类型
 * @author huayunlong
 * @date 2018-7-12
 */
public class HArray<E> {

    private int size;

    private E[] data;

    public HArray(int capacity){
        data = (E[]) new Object[capacity];
    }

    public HArray(){
        this(10);
    }

    public int length(){
        return data.length;
    }

    public void add(E e){
        if (size >= data.length) {
            resize(data.length * 2);
        }
        data[size] = e;
        size++;
    }


    public E get(int index){
        return data[index];
    }


    public void remove(int index){
        if (index<0 ||index>size){
            throw new ArrayIndexOutOfBoundsException("下标异常!");
        }
        for (int i = index; i <size ; i++) {
            data[i] = data[i + 1];
        }
        size--;
        if (size <= data.length / 4) {
            this.resize(data.length/2);
        }
    }

    public void removeFirst(){
        this.remove(0);
    }

    public void removeLast(){
        this.remove(size-1);
    }


    public void loopRemove(){

    }


    private void resize(int i) {
        E[] temp = (E[]) new Object[i];
        for (int j = 0; j <size ; j++) {
            temp[j] = data[j];
        }
        this.data = temp;
    }


    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("数组:[");
        for (int i = 0; i <data.length ; i++) {
            sb.append(data[i]);
            if (i < data.length-1) {
                sb.append(",");
            }
        }
        sb.append("]  "+data.length);
        return sb.toString();
    }

}
